package com.astrofizzbizz.whatchadoing;

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.WindowEvent;
import java.text.ParseException;

import javax.swing.BoxLayout;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.KeyStroke;
import javax.swing.SwingConstants;
import javax.swing.UIManager;

import com.astrofizzbizz.utilities.DateUtilties;
import com.astrofizzbizz.utilities.DpmSwingUtilities;
import com.astrofizzbizz.utilities.StatusPanel;
import com.astrofizzbizz.whatchadoing.WhatchaDoing.WhatchaDoingException;
import com.toedter.calendar.JDateChooser;
import com.toedter.components.JSpinField;


public class WhatchaDoingGui extends JFrame
{
	private static final long serialVersionUID = 3155283883049454997L;
	public static final String delim = System.getProperty("file.separator");
	public static final String newline = System.getProperty("line.separator");
	
	private JMenuBar mainMenuBar;
	private JPanel mainPane;
	protected StatusPanel statusBar;
	ClassLoader loader;

	protected String version = "v1.0";
	protected String versionDate = "April 1, 2013";
	
	JDateChooser startDateChooser;
	JDateChooser stopDateChooser;
	private JSpinField startTimeHoursField     = new JSpinField(0, 23) ;
	private JSpinField startTimeMinsField     = new JSpinField(0, 59);
	private JSpinField stopTimeHoursField     = new JSpinField(0, 23);
	private JSpinField stopTimeMinsField     = new JSpinField(0, 59);
	private JSpinField numNotifyPerDayField     = new JSpinField(1, 100);
	WhatchaDoing whatchaDoing;
	JButton startButton;
	JButton stopButton;


	public WhatchaDoingGui(String frametitle, String statusBarTitle, int numStatusLines, String imageIconSource)
	{
		super(frametitle);
		statusBar = new StatusPanel(numStatusLines, statusBarTitle);
		
		loader  = Thread.currentThread().getContextClassLoader();
		ImageIcon  logoIcon = new ImageIcon(loader.getResource(imageIconSource));
        setIconImage(logoIcon.getImage());
        try 
        {
            UIManager.setLookAndFeel( UIManager.getCrossPlatformLookAndFeelClassName());
//            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
        } catch (Exception e) {}
        
        try 
        {
            whatchaDoing = new WhatchaDoing();
		} catch (WhatchaDoingException e) 
		{
			DpmSwingUtilities.messageDialog(e.getMessage(), this);
		}
        whatchaDoing.setWhatchaDoingGui(this);
		startDateChooser = new JDateChooser(whatchaDoing.getStartDate());
		startDateChooser.setPreferredSize(
				new Dimension(startDateChooser.getPreferredSize().width + 10, startDateChooser.getPreferredSize().height));
		stopDateChooser = new JDateChooser(whatchaDoing.getStopDate());
		stopDateChooser.setPreferredSize(
				new Dimension(startDateChooser.getPreferredSize().width + 10, startDateChooser.getPreferredSize().height));
        numNotifyPerDayField.setValue(whatchaDoing.getNumNotifyPerDay());
    	startTimeHoursField.setValue(DateUtilties.getHours(whatchaDoing.getStartDate()));
    	startTimeMinsField.setValue(DateUtilties.getMins(whatchaDoing.getStartDate()));
    	stopTimeHoursField.setValue(DateUtilties.getHours(whatchaDoing.getStopDate()));
    	stopTimeMinsField.setValue(DateUtilties.getMins(whatchaDoing.getStopDate()));
       
        mainMenuBar = makeMenu();
        setJMenuBar(mainMenuBar);
       
		mainPane= new JPanel();
        setupMainPanel();
		mainPane.addMouseListener(new WhatchaDoingGuiMouseListeners());
        getContentPane().setLayout(new BorderLayout(5,5));
		getContentPane().add(mainPane, BorderLayout.CENTER);
		getContentPane().add(statusBar.getScrollPane(), java.awt.BorderLayout.SOUTH);  
		statusBar.setText("Welcome");
		pack();
        Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
        
        // Determine the new location of the window
        int w = this.getSize().width;
        int h = this.getSize().height;
        int x = (dim.width-w)/2;
        int y = (dim.height-h)/2;
        
        // Move the window
        this.setLocation(x, y);
		setVisible(true);
		statusBar.getScrollPane().setMinimumSize(statusBar.getScrollPane().getSize());
		statusBar.getScrollPane().setPreferredSize(statusBar.getScrollPane().getSize());

        
        addWindowListener(new java.awt.event.WindowAdapter() 
        {
            public void windowClosing(WindowEvent winEvt) 
            {
            	quitProgram();            
            }
        });

	}
	protected void setupMainPanel()
	{
		mainPane.setLayout(new BoxLayout(mainPane, BoxLayout.Y_AXIS));
		JLabel hourLabel1 = new JLabel("Hour: ");
		JLabel hourLabel2 = new JLabel("Hour: ");
		JLabel minLabel1 = new JLabel("Min: ");
		JLabel minLabel2 = new JLabel("Min: ");
		JLabel notifyLabel = new JLabel("Alerts per day: ");
		hourLabel1.setHorizontalAlignment(SwingConstants.RIGHT);
		hourLabel2.setHorizontalAlignment(SwingConstants.RIGHT);
		minLabel1.setHorizontalAlignment(SwingConstants.RIGHT);
		minLabel2.setHorizontalAlignment(SwingConstants.RIGHT);
//		notifyLabel.setHorizontalAlignment(SwingConstants.RIGHT);
		
		JPanel infoPanel= new JPanel();
		infoPanel.setLayout(new GridLayout(3,6));
		infoPanel.add(new JLabel("Start Day:"));
		infoPanel.add(startDateChooser);
		infoPanel.add(hourLabel1);
		infoPanel.add(startTimeHoursField);
		infoPanel.add(minLabel1);
		infoPanel.add(startTimeMinsField);

		infoPanel.add(new JLabel("Stop Day:"));
		infoPanel.add(stopDateChooser);
		infoPanel.add(hourLabel2);
		infoPanel.add(stopTimeHoursField);
		infoPanel.add(minLabel2);
		infoPanel.add(stopTimeMinsField);
		
		infoPanel.add(notifyLabel);
		infoPanel.add(numNotifyPerDayField);
		infoPanel.add(new JLabel(""));
		infoPanel.add(new JLabel(""));
		infoPanel.add(new JLabel(""));
		infoPanel.add(new JLabel(""));

		JPanel startStopPanel= new JPanel();
		startStopPanel.setLayout(new FlowLayout());
		startButton = new JButton();
		startButton.setIcon(new ImageIcon(loader.getResource("com/astrofizzbizz/utilities/files/start.jpg")));
		stopButton = new JButton();
		stopButton.setIcon(new ImageIcon(loader.getResource("com/astrofizzbizz/utilities/files/stop.jpg")));
		startButton.addActionListener(new WhatchaDoingGuiActionListeners("startButton", this));
		stopButton.addActionListener(new WhatchaDoingGuiActionListeners("stopButton", this));
		
		startStopPanel.add(startButton);
		startStopPanel.add(stopButton);
		stopButton.setEnabled(false);
		if ((whatchaDoing.getEmailAddress() == null) || (whatchaDoing.getEmailPassword() == null)) 
			startButton.setEnabled(false);
		
		mainPane.add(infoPanel);
		mainPane.add(startStopPanel);
		 
	}
	void setupGmail()
	{
		GmailLoginDialog gmailLoginDialog 
			= new GmailLoginDialog(this, 
				whatchaDoing.getEmailName(), whatchaDoing.getEmailAddress(), whatchaDoing.getEmailPassword());
		whatchaDoing.setEmailName(gmailLoginDialog.getGmailName()); 
		whatchaDoing.setEmailAddress(gmailLoginDialog.getGmailLogin()); 
		whatchaDoing.setEmailPassword(gmailLoginDialog.getGmailPassword()); 
		gmailLoginDialog.dispose();
		if ((whatchaDoing.getEmailAddress() != null) && (whatchaDoing.getEmailPassword() != null)) 
			startButton.setEnabled(true);
		this.setTitle("Whatcha Doing " + gmailLoginDialog.getGmailName() +"?");
	}
	void startPestering()
	{
		if ((whatchaDoing.getEmailAddress() == null) || (whatchaDoing.getEmailPassword() == null)) 
		{
			DpmSwingUtilities.messageDialog("Invalid Email", this);
			return;
		}
		try 
		{
			int [] dayMonthYearHourMinuteSecond  = DateUtilties.dayMonthYearHourMinuteSecond(startDateChooser.getDate());
			dayMonthYearHourMinuteSecond[3] = startTimeHoursField.getValue();
			dayMonthYearHourMinuteSecond[4] = startTimeMinsField.getValue();
			dayMonthYearHourMinuteSecond[5] = 0;
			whatchaDoing.setStartDate(DateUtilties.makeDate(dayMonthYearHourMinuteSecond));
			
			dayMonthYearHourMinuteSecond  = DateUtilties.dayMonthYearHourMinuteSecond(stopDateChooser.getDate());
			dayMonthYearHourMinuteSecond[3] = stopTimeHoursField.getValue();
			dayMonthYearHourMinuteSecond[4] = stopTimeMinsField.getValue();
			dayMonthYearHourMinuteSecond[5] = 0;
			whatchaDoing.setStopDate(DateUtilties.makeDate(dayMonthYearHourMinuteSecond));
			
			whatchaDoing.setNumNotifyPerDay(numNotifyPerDayField.getValue());
			
			stopButton.setEnabled(true);
			startButton.setEnabled(false);
			Thread thread = new Thread(whatchaDoing);
			thread.start();
		} 
		catch (ParseException e) 
		{
			DpmSwingUtilities.messageDialog(e.getMessage(), this);
			return;
		} 		
	}
	void stopPestering()
	{
		whatchaDoing.setStopPestering(true);
		stopButton.setEnabled(false);
		startButton.setEnabled(true);
	}
	protected  JMenuBar makeMenu()
	{
		JMenuBar menuBar = new JMenuBar();
		String menuText[] = {"File", "Gmail", "Help"};
        String subMenuText[][] =
        {
    		{"Open","Exit"},
    		{"Account Info"},
    		{"Help", "About"}
    	};

        for (int i = 0; i < menuText.length; i++)
        {
            JMenu menu = new JMenu(menuText[i]);
            menuBar.add (menu);
            
            for (int j = 0; j < subMenuText[i].length; j++)
            {
                JMenuItem item = new JMenuItem(subMenuText[i][j]);
                menu.add (item);
                item.addActionListener(new WhatchaDoingGuiActionListeners(menuText[i] + "." +subMenuText[i][j], this));
        		if (subMenuText[i][j].equals("Open")) item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_O, ActionEvent.CTRL_MASK));
        		if (subMenuText[i][j].equals("Exit")) item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_Q, ActionEvent.CTRL_MASK));
         		if (subMenuText[i][j].equals("Help")) item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_H, ActionEvent.CTRL_MASK));
         		if (subMenuText[i][j].equals("About")) item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_A, ActionEvent.CTRL_MASK));
            }
        }
        
        return menuBar;
    }
	protected void quitProgram()
	{
		dispose();
		System.exit(0);
	}
	private class WhatchaDoingGuiActionListeners implements ActionListener
	{
		WhatchaDoingGui whatchaDoingGui;
		String actionString = "";
		WhatchaDoingGuiActionListeners(String actionString, WhatchaDoingGui whatchaDoingGui)
		{
			this.actionString = actionString;
			this.whatchaDoingGui = whatchaDoingGui;
		}
		@Override
		public void actionPerformed(ActionEvent arg0) 
		{
			if (actionString.equals("Help.About"))
			{
				DpmSwingUtilities.messageDialog("Whatcha Doing? " + version + "\n" + "Last Updated " + versionDate, whatchaDoingGui);
			}
			if (actionString.equals("Gmail.Account Info"))
			{
				setupGmail();
			}
			if (actionString.equals("startButton"))
			{
				startPestering();
			}
			if (actionString.equals("stopButton"))
			{
				whatchaDoingGui.whatchaDoing.setStopPestering(true);
			}
		}
		
	}
	private class WhatchaDoingGuiMouseListeners implements MouseListener
	{
		@Override
		public void mouseClicked(MouseEvent arg0) {}
		@Override
		public void mouseEntered(MouseEvent arg0) {}
		@Override
		public void mouseExited(MouseEvent arg0) {}
		@Override
		public void mousePressed(MouseEvent arg0) {}
		@Override
		public void mouseReleased(MouseEvent arg0) {}
	}
	public static void main(String[] args) 
	{
		new WhatchaDoingGui("Whatcha Doing?", "Info", 4, "com/astrofizzbizz/utilities/files/questionMark.jpg");
	}

}
